#include "download_file.h"

#include <QDir>

#include "client_define.h"

download_file::download_file(QObject *parent) : QObject{parent} {

}

void download_file::Download(QString path) {
    if (path.isEmpty())
        return;

    QDir dir(path);//文件夹路径
    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); //过滤去除文件夹下的.目录与..目录
    QStringList fileEntryList = dir.entryList(); //获取目录下的所有条目

    QString mp3_files = ""; // 文件夹下的mp3文件名
    mp3_files.append(username).append("{##}");
    int cnt = 0;
    for (const auto &file_name: fileEntryList) {
        if (file_name.endsWith(".mp3")) {
            mp3_files.append(file_name).append("{##}");
            ++cnt;
            // if (cnt >= 2)
            //     break;
        }
    }
    qDebug() << mp3_files;

    if (!is_connected) {
        this->file_socket = new QTcpSocket(this);
        file_socket->abort();
        file_socket->connectToHost(FILE_SERVER_DOWNLOAD_HOST, FILE_SERVER_DOWNLOAD_PORT);
    }

    connect(file_socket, &QTcpSocket::connected, this, [&]() {
        qDebug() << "download file_socket->connected()";
        is_connected = true;
    });

    this->file_socket->write(mp3_files.toUtf8());

    isStart = true;
    connect(file_socket, &QTcpSocket::readyRead, this, &download_file::recvFile);
    connect(file_socket, &QTcpSocket::disconnected, this, [&]() {
        qDebug() << "disconnected";
        is_connected = false;
        //断开连接
        file_socket->close();
        file_socket->deleteLater();
        emit recvOver();
    });
}

void download_file::recvFile() {
    //取出接收的内容
    QByteArray buf = file_socket->readAll();
    if (isStart) {
        //接收头部
        isStart = false;
        //解析头部
        file.close();
        qDebug() << QString(buf);
        filename = QString(buf).section("##", 0, 0);
        file_size = QString(buf).section("##", 1, 1).toInt();
        if (file_size == 0) {
            isStart = true;
            file.close();
            return;
        }
        rec_file_size = 0;
        //打开文件
        file.setFileName(filename);
        qDebug() << filename << " " << file_size;
        bool isOk = file.open(QIODevice::WriteOnly);
        if (!isOk) {
            file.close();
            isStart = true;
            return;
        }
    } else {
        qint64 len = file.write(buf);
        if (len > 0) {
            rec_file_size += len;//累计接收大小
        }
        if (rec_file_size == file_size) {
            file.close();
            isStart = true;
            qDebug() << "rec!!";
        }
    }
}

void download_file::setUsername(const QString &new_username) {
    username = new_username;
}
